package org.ws.httphelper.spring;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.ws.httphelper.HttpHelper;
import org.ws.httphelper.builder.HttpHelperBuilder;
import org.ws.httphelper.model.template.RequestTemplate;
import org.ws.httphelper.template.DefaultRequestTemplate;

@Configuration
@EnableConfigurationProperties({HttpHelperProperties.class})
public class DefaultHttpHelperConfiguration {

    @Bean("httpHelper")
    @ConditionalOnMissingBean(name = {"httpHelper"})
    public HttpHelper httpHelper(HttpHelperProperties httpHelperProperties){
        String defaultTemplate = httpHelperProperties.getDefaultTemplate();
        RequestTemplate template = null;
        if(StringUtils.equals("okHttpGetHtml",defaultTemplate)){
            template = DefaultRequestTemplate.okHttpGetHtml();
        }
        else if(StringUtils.equals("webGetHtml",defaultTemplate)){
            template = DefaultRequestTemplate.webGetHtml();
        }
        else if(StringUtils.equals("okHttpPostJson",defaultTemplate)){
            template = DefaultRequestTemplate.okHttpPostJson();
        }
        else if(StringUtils.equals("okHttpPostXml",defaultTemplate)){
            template = DefaultRequestTemplate.okHttpPostXml();
        }
        else {
            Assert.notNull(httpHelperProperties.getRequest(),"http-helper.request must be not null.");
            template = HttpHelperPropertiesBuilder.builder(httpHelperProperties).build();
        }
        return HttpHelperBuilder.builder().builderByTemplate(template);
    }

}
